package cn.zero.letaomallspringboot.controller;

import cn.zero.letaomallspringboot.Constant.ResultCode;
import cn.zero.letaomallspringboot.common.PageResult;
import cn.zero.letaomallspringboot.common.Result;
import cn.zero.letaomallspringboot.entity.User;
import cn.zero.letaomallspringboot.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "用户管理", description = "用户的查询、创建、更新、删除、密码修改、状态调整等操作")
@RestController
@RequestMapping("/user")
public class UserController {
    private final IUserService userService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    public UserController(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 分页查询用户列表
     */
    @Operation(summary = "分页查询用户列表", description = "支持按用户名、手机号、邮箱、用户状态、注册时间范围筛选")
    @GetMapping("/list")
    public Result<PageResult<User>> userList(
            @Parameter(description = "页码（默认1）", required = false, example = "1")
            @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页条数（默认10）", required = false, example = "10")
            @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "用户名（模糊查询）", required = false)
            @RequestParam(required = false) String username,
            @Parameter(description = "手机号（精确查询）", required = false)
            @RequestParam(required = false) String phone,
            @Parameter(description = "邮箱（模糊查询）", required = false)
            @RequestParam(required = false) String email,
            @Parameter(description = "用户状态（0-禁用，1-正常，2-待验证）", required = false)
            @RequestParam(required = false) Integer userStatus,
            @Parameter(description = "注册开始时间（格式：yyyy-MM-dd HH:mm:ss）", required = false)
            @RequestParam(required = false) String startRegisterTime,
            @Parameter(description = "注册结束时间（格式：yyyy-MM-dd HH:mm:ss）", required = false)
            @RequestParam(required = false) String endRegisterTime) {

        // 封装筛选参数
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("size", size);
        if (username != null && !username.trim().isEmpty()) {
            params.put("username", username.trim());
        }
        if (phone != null && !phone.trim().isEmpty()) {
            params.put("phone", phone.trim());
        }
        if (email != null && !email.trim().isEmpty()) {
            params.put("email", email.trim());
        }
        if (userStatus != null) {
            params.put("userStatus", userStatus);
        }
        if (startRegisterTime != null && !startRegisterTime.trim().isEmpty()) {
            params.put("startRegisterTime", startRegisterTime.trim());
        }
        if (endRegisterTime != null && !endRegisterTime.trim().isEmpty()) {
            params.put("endRegisterTime", endRegisterTime.trim());
        }

        try {
            PageResult<User> pageResult = userService.getUserList(params);
            return Result.success(pageResult);
        } catch (Exception e) {
            logger.error("分页查询用户列表失败", e);
            return Result.fail(ResultCode.DB_ERROR, "用户列表查询失败");
        }
    }

    /**
     * 根据ID查询用户详情
     */
    @Operation(summary = "根据ID查询用户详情", description = "返回用户完整信息（不含密码明文，仅存储加密后的密码）")
    @GetMapping("/{id}")
    public Result<User> getUser(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Long id) {
        logger.info("查询用户详情: {}", id);

        try {
            User user = userService.getUserById(id);
            if (user == null) {
                return Result.fail(ResultCode.USER_NOT_EXIST); // 用户不存在
            }
            // 安全处理：隐藏加密后的密码（避免泄露）
            user.setPassword(null);
            return Result.success(user);
        } catch (Exception e) {
            logger.error("查询用户详情失败，用户ID：{}", id, e);
            return Result.fail(ResultCode.DB_ERROR, "用户详情查询失败");
        }
    }

    /**
     * 创建新用户（注册）
     */
    @Operation(summary = "创建新用户", description = "支持用户注册，自动加密密码并补全默认昵称、头像")
    @PostMapping
    public Result<User> addUser(@RequestBody User user) {
        logger.info("创建新用户: 手机号={}", user.getPhone());

        // 简单参数校验
        if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_MISS, "手机号不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_MISS, "密码不能为空");
        }

        try {
            boolean success = userService.createUser(user);
            if (!success) {
                return Result.fail(ResultCode.DB_ERROR, "用户创建失败");
            }
            // 安全处理：返回时隐藏密码
            user.setPassword(null);
            return Result.success(user, "用户注册成功");
        } catch (IllegalArgumentException e) {
            // 业务异常（如手机号已注册）
            logger.warn("创建用户业务校验失败: {}", e.getMessage());
            return Result.fail(ResultCode.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("创建新用户失败", e);
            return Result.fail(ResultCode.DB_ERROR, "用户创建失败");
        }
    }

    /**
     * 更新用户信息（不含密码）
     */
    @Operation(summary = "更新用户信息", description = "仅更新非null字段，不支持密码修改（密码需单独调用修改接口）")
    @PutMapping("/{id}")
    public Result<User> updateUser(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Long id,
            @RequestBody User user) {
        logger.info("更新用户: ID={}, 信息={}", id, user);

        // 验证用户是否存在
        try {
            User existingUser = userService.getUserById(id);
            if (existingUser == null) {
                return Result.fail(ResultCode.USER_NOT_EXIST);
            }

            // 确保更新的是指定ID的用户
            user.setId(id);
            // 禁止通过此接口修改密码
            user.setPassword(null);

            boolean success = userService.updateUser(user);
            if (!success) {
                return Result.fail(ResultCode.DB_ERROR, "用户信息更新失败");
            }

            // 安全处理：返回时隐藏密码
            user.setPassword(null);
            return Result.success(user, "用户信息更新成功");
        } catch (IllegalArgumentException e) {
            logger.warn("更新用户业务校验失败: {}", e.getMessage());
            return Result.fail(ResultCode.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("更新用户失败，用户ID：{}", id, e);
            return Result.fail(ResultCode.DB_ERROR, "用户信息更新失败");
        }
    }

    /**
     * 根据ID删除用户
     */
    @Operation(summary = "根据ID删除用户", description = "物理删除用户（实际项目建议改为逻辑删除，新增is_delete字段）")
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Long id) {
        logger.info("删除用户: {}", id);

        try {
            User user = userService.getUserById(id);
            if (user == null) {
                return Result.fail(ResultCode.USER_NOT_EXIST);
            }

            boolean success = userService.deleteUser(id);
            if (!success) {
                return Result.fail(ResultCode.DB_ERROR, "用户删除失败");
            }
            return Result.success(null, "用户删除成功");
        } catch (Exception e) {
            logger.error("删除用户失败，用户ID：{}", id, e);
            return Result.fail(ResultCode.DB_ERROR, "用户删除失败");
        }
    }

    /**
     * 批量删除用户
     */
    @Operation(summary = "批量删除用户", description = "支持一次性删除多个用户，传入用户ID列表")
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteUser(
            @Parameter(description = "用户ID列表", required = true, example = "[1,2,3]")
            @RequestBody List<Long> ids) {
        logger.info("批量删除用户: {}", ids);

        // 参数校验：ID列表不能为空
        if (ids == null || ids.isEmpty()) {
            return Result.fail(ResultCode.PARAM_MISS, "请选择要删除的用户");
        }

        try {
            boolean success = userService.batchDeleteUser(ids);
            if (!success) {
                return Result.fail(ResultCode.DB_ERROR, "用户批量删除失败");
            }
            return Result.success(null, "用户批量删除成功");
        } catch (IllegalArgumentException e) {
            logger.warn("批量删除用户业务校验失败: {}", e.getMessage());
            return Result.fail(ResultCode.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("批量删除用户失败，ID列表：{}", ids, e);
            return Result.fail(ResultCode.DB_ERROR, "用户批量删除失败");
        }
    }

    /**
     * 更新用户密码
     */
    @Operation(summary = "更新用户密码", description = "需传入用户ID和新密码，系统自动加密存储")
    @PatchMapping("/{id}/password")
    public Result<Void> updateUserPassword(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Long id,
            @Parameter(description = "新密码", required = true, example = "newPassword123")
            @RequestParam String newPassword) {
        logger.info("更新用户密码: 用户ID={}", id);

        // 参数校验
        if (newPassword == null || newPassword.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_MISS, "新密码不能为空");
        }

        try {
            // 校验用户是否存在
            User user = userService.getUserById(id);
            if (user == null) {
                return Result.fail(ResultCode.USER_NOT_EXIST);
            }

            boolean success = userService.updateUserPassword(id, user.getPassword(), newPassword);
            if (!success) {
                return Result.fail(ResultCode.DB_ERROR, "密码更新失败");
            }
            return Result.success(null, "密码更新成功");
        } catch (IllegalArgumentException e) {
            logger.warn("更新用户密码业务校验失败: {}", e.getMessage());
            return Result.fail(ResultCode.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("更新用户密码失败，用户ID：{}", id, e);
            return Result.fail(ResultCode.DB_ERROR, "密码更新失败");
        }
    }

    /**
     * 更新用户状态
     */
    @Operation(summary = "更新用户状态", description = "支持状态：0-禁用（禁止登录）、1-正常、2-待验证（手机号未验证）")
    @PatchMapping("/{id}/status")
    public Result<User> updateUserStatus(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Long id,
            @Parameter(description = "目标状态（0-禁用，1-正常，2-待验证）", required = true, example = "1")
            @RequestParam Integer userStatus) {
        logger.info("更新用户状态: 用户ID={}, 目标状态={}", id, userStatus);

        // 参数校验：状态值必须是0/1/2
        if (userStatus == null || (userStatus != 0 && userStatus != 1 && userStatus != 2)) {
            return Result.fail(ResultCode.PARAM_ERROR, "用户状态无效（仅支持0-禁用、1-正常、2-待验证）");
        }
        try {
            // 校验用户是否存在
            User user = userService.getUserById(id);
            if (user == null) {
                return Result.fail(ResultCode.USER_NOT_EXIST);
            }

            boolean success = userService.updateUserStatus(id, userStatus);
            if (!success) {
                return Result.fail(ResultCode.DB_ERROR, "用户状态更新失败");
            }

            // 更新返回结果中的状态
            user.setUserStatus(userStatus);
            // 安全处理：隐藏密码
            user.setPassword(null);
            return Result.success(user, "用户状态更新成功");
        } catch (IllegalArgumentException e) {
            logger.warn("更新用户状态业务校验失败: {}", e.getMessage());
            return Result.fail(ResultCode.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("更新用户状态失败，用户ID：{}", id, e);
            return Result.fail(ResultCode.DB_ERROR, "用户状态更新失败");
        }
    }
}